<?php

$method_map = array(
"" => "index",
"list" => "list_products"
);

include("baseController.php");
require_once 'data/datautils.php';
function index() {
    showView('base',array('title' => 'Hello','content' => 'Hello, World!'));
}

function list_products() {
    global $req;
    $cat = (int)$req['category'];
    $categories = array();
    if ($cat==0) {
        $categories = db_select_all_where('categories', '`parent_id` = 0');
    } else {
        $par = db_query_result('SELECT parent_id FROM `categories` WHERE id = '.$cat);
        if ($par === false) {
            $par = 0;
            $cat = 0;
            $categories = db_select_all_where('categories', '`parent_id` = 0');
        } elseif ($par == 0) {
            // 1st level
            $categories = db_select_all_where('categories', '`parent_id` = 0 AND id <= '.$cat);
            $categories = array_merge($categories,db_select_all_where('categories', '`parent_id` = '.$cat));
            $categories = array_merge($categories,db_select_all_where('categories', '`parent_id` = 0 AND id > '.$cat));
        } else {
            // 2nd level
            $categories = db_select_all_where('categories', '`parent_id` = 0 AND id <= '.$par);
            $categories = array_merge($categories,db_select_all_where('categories', '`parent_id` = '.$par));
            $categories = array_merge($categories,db_select_all_where('categories', '`parent_id` = 0 AND id > '.$par));
        }
    }
    $products = db_select_all_where('products', '`category_id` = '.$cat);
    showView('list_products', array('categories' => $categories, 'products' => $products));
}